package com.ruoyi.walmart.service.order.impl;

import com.ruoyi.walmart.domain.order.*;
import com.ruoyi.walmart.mapper.order.OrderMapper;
import com.ruoyi.walmart.service.order.OrderChargeService;
import com.ruoyi.walmart.service.order.OrderItemService;
import com.ruoyi.walmart.service.order.OrderService;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderChargeService orderChargeService;

    @Override
    @Transactional
    public int insertAll(List<AllOrder> orderList) {
        return orderMapper.insertAll(orderList);
    }

    @Override
    public Date orderDate(Long authId) {
        return orderMapper.orderDate(authId);
    }

    @Override
    public List<AllOrder> selectAllList(Long authId) {
        return orderMapper.selectAllList(authId);
    }

    @Override
    @Transactional
    public int deleteAuthId(Long authId) {
        return orderMapper.deleteAuthId(authId);
    }

    @Override
    public List<String> customerOrderId(Long authId) {
        return orderMapper.customerOrderId(authId);
    }

    @Override
    public List<AllOrder> selectOrderAuthId(VoOrder order) {
        return orderMapper.selectOrderAuthId(order);
    }

    /** 查询最后创建的时间（推迟一个小时） */
    @Override
    public Date delayOrderDate(Long authId) {
        return orderMapper.delayOrderDate(authId);
    }

    /**
     * **删除 & 订单数据插入（确保事务回滚）**
     * - **先删除旧数据，再插入新数据**
     * - **如果 `insertAll()` 失败，删除操作也会回滚**
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteAndSaveData(Long authId,List<String> stringList,List<OrderItem> orderItems, List<OrderCharge> orderCharges, List<AllOrder> orders) {
        try {
            // **1️⃣ 删除本地 "1 小时前" 的数据**
            if (stringList != null && !stringList.isEmpty()) {
                orderItemService.deleteItem(stringList);
                orderChargeService.deleteCharge(stringList);
                orderMapper.deleteAuthId(authId);
            }
            // **2️⃣ 过滤出唯一性约束不会冲突的数据**
            // **批量查询数据库中已存在的purchaseOrderIds**
            if (orders != null && !orders.isEmpty()) {
                List<String> purchaseOrderIds = orders.stream()
                        .map(AllOrder::getPurchaseOrderId)
                        .collect(Collectors.toList());

                // **批量查询数据库中已存在的purchaseOrderIds**
                Set<String> existingOrderIds = new HashSet<>(orderMapper.findExistingPurchaseOrderIds(purchaseOrderIds));

                // **过滤掉已存在的订单**
                List<AllOrder> validOrders = orders.stream()
                        .filter(order -> !existingOrderIds.contains(order.getPurchaseOrderId()))
                        .collect(Collectors.toList());

                // **3️⃣ 执行插入操作**
                if (!validOrders.isEmpty()) {
                    batchInsert(validOrders, 1000, orderMapper::insertAll); // 分页插入
                }

            }
            // **批量查询数据库中已存在的purchaseOrderIds**
            if (orderItems != null && !orderItems.isEmpty()) {
                List<String> purchaseOrderIds = orderItems.stream()
                        .map(OrderItem::getPurchaseOrderId)
                        .collect(Collectors.toList());

                // **批量查询数据库中已存在的purchaseOrderIds**
                Set<String> existingOrderItemIds = new HashSet<>(orderItemService.findExistingItemPurchaseOrderIds(purchaseOrderIds));

                // **过滤掉已存在的订单**
                List<OrderItem> validOrderItems = orderItems.stream()
                        .filter(orderItem -> !existingOrderItemIds.contains(orderItem.getPurchaseOrderId()))
                        .collect(Collectors.toList());

                // **3️⃣ 执行插入操作**
                if (!validOrderItems.isEmpty()) {
                    batchInsert(validOrderItems, 1000, orderItemService::insertAll);
                }
            }

            // **批量查询数据库中已存在的purchaseOrderIds**
            if (orderCharges != null && !orderCharges.isEmpty()) {
                List<String> purchaseOrderIds = orderCharges.stream()
                        .map(OrderCharge::getPurchaseOrderId)
                        .collect(Collectors.toList());

                // **批量查询数据库中已存在的purchaseOrderIds**
                Set<String> existingOrderChargesIds = new HashSet<>(orderChargeService.findExistingChatgesPurchaseOrderIds(purchaseOrderIds));

                // **过滤掉已存在的订单**
                List<OrderCharge> validOrderCharges = orderCharges.stream()
                        .filter(orderCharge -> !existingOrderChargesIds.contains(orderCharge.getPurchaseOrderId()))
                        .collect(Collectors.toList());

                // **3️⃣ 执行插入操作**
                if (!validOrderCharges.isEmpty()) {
                    batchInsert(validOrderCharges, 1000, orderChargeService::insertAll);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("订单数据处理失败，已回滚", e);
        }
    }

    private <T> void batchInsert(List<T> list, int batchSize, Consumer<List<T>> insertFunc) {
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<T> batch = list.subList(i, end);
            insertFunc.accept(batch);
        }
    }
}
